/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-09-10
*/
package com.rzico.order.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.account.entity.Refunds;
import com.rzico.account.model.Attach;
import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.service.EnterpriseService;
import com.rzico.entity.Filter;
import com.rzico.entity.Pageable;
import com.rzico.entity.PageResult;
import com.rzico.exception.CustomException;
import com.rzico.order.entity.GroupBuy;
import com.rzico.order.entity.GroupPeriod;
import com.rzico.order.entity.GroupProduct;
import com.rzico.order.service.GroupBuyService;
import com.rzico.order.service.GroupOrderService;
import com.rzico.order.service.GroupPeriodService;
import com.rzico.order.service.GroupProductService;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.Api;
import com.rzico.util.StringUtils;

import java.util.*;

/**
 * 团购管理控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-09-10
 */
@Api(description = "团购管理接口")
@RestController
@RequestMapping("/admin/groupBuy")
public class GroupBuyAdminController extends BaseController {

    @Autowired
    private GroupBuyService groupBuyService;

    @Autowired
    private GroupProductService groupProductService;

    @Autowired
    private GroupOrderService groupOrderService;

    @Autowired
    private GroupPeriodService groupPeriodService;

    @Autowired
    private EnterpriseService enterpriseService;



    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 分页查询团购管理
     *
     * @return
    */
    @ApiOperation("分页查询团购管理")
    @GetMapping("/list")
    @ApiImplicitParams({@ApiImplicitParam(name = "startDate", value = "开始时间", dataType = "String", paramType = "query") ,
            @ApiImplicitParam(name = "endDate", value = "结束时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态（0.待审核，1.已审核, 2.已完成,3.已取消）", dataType = "String", paramType = "query")
    })
    public CommResult<GroupBuy> list(Date startDate, Date endDate,Integer status, Pageable pageable) {
        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);
        if (startDate!=null){
           params.put("startDate", startDate);
        }
        if (endDate!=null){
           params.put("endDate", DateUtils.addMilliseconds(DateUtils.addDays(endDate,1),-1));
        }

        if (status!=null){
            params.put("status", status);
        }

        Enterprise enterprise = enterpriseService.getCurrent();
        if (enterprise!=null) {
            params.put("enterpriseId", enterprise.getId());
        } else {
            return CommResult.error("没有开通企业");
        }

        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<GroupBuy> list = groupBuyService.selectList(params);
//        for (GroupBuy groupBuy:list) {
//            if (groupBuy.getPeriodId()!=null && groupBuy.getStatus().equals(1)) {
//                GroupPeriod groupPeriod = groupPeriodService.selectByPrimaryKey(groupBuy.getPeriodId());
//                Date c = groupPeriod.getCreateDate();
//                c = DateUtils.addSeconds(c, groupBuy.getDuration());
//                if (c.before(new Date())) {
//                    groupBuy.setStatus(2);
//                }
//            }
//
//        }
        PageResult<GroupBuy> pageResult = new PageResult<GroupBuy>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);
    }

    /**
     * 查询单条团购管理
     *
     * @return
    */
    @ApiOperation("查询单条团购管理")
    @GetMapping("/find/{id}")
    public CommResult<GroupBuy> find(@PathVariable String id) {

        GroupBuy result = groupBuyService.findById(id);
        result.setArticle(result.getMetaAndContent());
        result.setItemList(groupProductService.getItemList(result.getId()));
        result.setOrderList(groupOrderService.getItemList(result.getPeriodId()));

        Map<String,Object> data = new HashMap<>();
        data.put("groupBuy",result);
        return CommResult.success(data);

    }

    /**
     * 保存团购管理
     *
     * @param groupBuy
     * @return
     */
    @ApiOperation("保存团购管理")
    @PostMapping("/save")
    public CommResult<GroupBuy> save(@RequestBody GroupBuy groupBuy) {

        Enterprise enterprise = enterpriseService.getCurrent();
        groupBuy.setEnterpriseId(enterprise.getId());
        groupBuy.setCreateDate(new Date());
        groupBuy.setDeleted(false);
        groupBuy.setBuyNum(0);
        if (groupBuy.getArticle()!=null) {
            groupBuy.setMeta(JSON.toJSONString(groupBuy.getArticle().getProductMeta()));
            groupBuy.setContent(groupBuy.getArticle().getContent());
        }
        int affectCount = groupBuyService.save(groupBuy);
        if (affectCount <= 0) {
            return CommResult.error();
        }
        GroupBuy result = groupBuyService.findById(groupBuy.getId());
        return CommResult.success(result);

    }


    /**
     * 批量删除团购管理
     *
     * @param ids
     * @return
     */
    @Log(desc = "批量删除团购管理", type = Log.LOG_TYPE.DEL)
    @ApiOperation("批量删除团购管理,ids用逗号拼接")
    @PostMapping("/del/{ids}")
    public CommResult<GroupBuy> del(@PathVariable String ids) {


        try {
            groupBuyService.deleteByIds(ids.split(","));
        } catch (Exception e) {
            return CommResult.error(e.getMessage());
        }
        return CommResult.success();

    }

    /**
     * 更新团购管理
     *
     * @param groupBuy
     * @return
     */
    @Log(desc = "更新团购管理", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("更新团购管理")
    @PostMapping("/update")
    public CommResult<GroupBuy> update(@RequestBody GroupBuy groupBuy) {

        GroupBuy buy = groupBuyService.selectByPrimaryKey(groupBuy.getId());
        if (!buy.getStatus().equals(0)) {
            return CommResult.error("已审核不能修改");
        }

        if (groupBuy.getArticle()!=null) {
            groupBuy.setMeta(JSON.toJSONString(groupBuy.getArticle().getProductMeta()));
            groupBuy.setContent(groupBuy.getArticle().getContent());
        }

        int affectCount = groupBuyService.update(groupBuy);
        if (affectCount <= 0){
            return CommResult.error();
        }
        GroupBuy result = groupBuyService.findById(groupBuy.getId());
        return CommResult.success(result);

    }

    /**
     * 审核团购
     *
     * @param groupBuy
     * @return
     */
    @Log(desc = "审核团购", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("审核团购")
    @PostMapping("/audit")
    public CommResult<GroupBuy> audit(@RequestBody GroupBuy groupBuy) {

        groupBuy = groupBuyService.selectByPrimaryKey(groupBuy.getId());
        if (!groupBuy.getStatus().equals(0)) {
            return CommResult.error("不在待审核");
        }

        groupBuy.setStatus(1);

        int affectCount = groupBuyService.audit(groupBuy);
        if (affectCount <= 0){
            return CommResult.error();
        }
        GroupBuy result = groupBuyService.findById(groupBuy.getId());
        return CommResult.success(result);

    }


    /**
     * 弃审团购
     *
     * @param groupBuy
     * @return
     */
    @Log(desc = "弃审团购", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("弃审团购")
    @PostMapping("/unAudit")
    public CommResult<GroupBuy> unAudit(@RequestBody GroupBuy groupBuy) {

        groupBuy = groupBuyService.selectByPrimaryKey(groupBuy.getId());
        if (!groupBuy.getStatus().equals(1)) {
            return CommResult.error("不在已审核");
        }

        if (groupBuy.getPeriodNum()>1 || groupBuy.getBuyNum()>0) {
            return CommResult.error("已执行不能弃审");
        }

        int affectCount = groupBuyService.unAudit(groupBuy);
        if (affectCount <= 0){
            return CommResult.error();
        }
        GroupBuy result = groupBuyService.findById(groupBuy.getId());
        return CommResult.success(result);

    }


    /**
     * 关闭团购
     *
     * @param id
     * @return
     */
    @Log(desc = "关闭团购", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("关闭团购,未完成的全额退款")
    @PostMapping("/cancel")
    public CommResult<GroupBuy> cancel(Long id) {

        GroupBuy groupBuy = groupBuyService.selectByPrimaryKey(id);

        List<Refunds> refundsList = groupBuyService.cancel(groupBuy);
        for (Refunds refunds:refundsList) {
            //TODO发送退款通知
            Attach attachQueue = new Attach();
            attachQueue.setCode("0000");
            attachQueue.setId(String.valueOf(refunds.getId()));
            attachQueue.setQueue("queue.refunds.submit");
            Message message = MessageBuilder
                    .withBody(JSON.toJSONString(attachQueue).getBytes())
                    .setContentType(MessageProperties.CONTENT_TYPE_JSON)
                    .build();
            CorrelationData correlationData = new CorrelationData();
            correlationData.setId(UUID.randomUUID().toString());
            logger.info("发送 MQ");
            rabbitTemplate.convertAndSend("directExchange",attachQueue.getQueue()+".key", message, correlationData);

        }

        GroupBuy result = groupBuyService.findById(groupBuy.getId());
        return CommResult.success(result);

    }

}
